<!--疫苗接种管理-->
<template>
  <!-- <div>
      疫苗接种管理
  </div>-->
  <BaseMainSlot>
    <template v-slot:zhactbar>
      <ActionBar
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-save="false"
        @add="add"
        @cancel="cancel"
        @edit="edit"
        @del="del"
        @save="save"
      />
    </template>
    <template v-slot:searchbox>
      <div class="label-input mr-20">
        <div class="label">个体名称:</div>
        <div class="input">
          <el-select
            v-model="bionIdName"
            clearable
            filterable
            placeholder="请选择"
            @focus="querybionId"
          >
            <el-option
              v-for="(item, index) in bionIdList"
              :key="index + 'bionId'"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </div>
      </div>
      <div class="label-input mr-20">
        <div class="label">耳标:</div>
        <div class="input">
          <div class="input">
            <el-input v-model="eagTag" placeholder="请输入耳标" clearable />
          </div>
        </div>
      </div>
      <div class="label-input mr-20">
        <div class="label">接种时间段:</div>
        <div class="input">
          <el-date-picker
            v-model="StartTime"
            align="right"
            type="date"
            value-format="timestamp"
            placeholder="请选择接种开始时间"
          />
        </div>
        <div class="input">
          <el-date-picker
            v-model="EndTime"
            align="right"
            type="date"
            value-format="timestamp"
            placeholder="请选择接种结束时间"
          />
        </div>
      </div>
      <div class="search ml-20">
        <img src="~@/assets/action-bar-icon/search.png" @click="queryPageList" />
      </div>
    </template>
    <template v-slot:content>
      <el-table
        ref="tableRef"
        :data="tableData"
        border
        stripe
        highlight-current-row
        max-height="88%"
        @row-click="handleEdit"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" />
        <el-table-column prop="eagTag" label="耳标" />
        <el-table-column prop="name" label="个体名称" width="150" />
        <el-table-column prop="facilityName" label="个体所在设施" width="200" />

        <el-table-column prop="vaccinumName" label="疫苗接种名称" />
        <el-table-column prop="untowardEffect" label="不良反应" />
        <el-table-column prop="vaccinationDate" label="接种时间">
          <template slot-scope="scope">
            {{
              scope.row.vaccinationDate
                ? $moment(scope.row.vaccinationDate).format(
                  "YYYY-MM-DD HH:mm:SS"
                )
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.gender === "MALE" ? "公" : "母" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="birthday" label="年龄" width="100" />
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="length"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
      <el-dialog title="疫苗信息管理" :visible.sync="addDialog">
        <el-form ref="addForm" :model="formData" label-position="left" label-width="100px">
          <el-row v-if="nowChanceStau === 'add'">
            <el-col :span="facilityList.length>0?12:24">
              <el-form-item label="羊舍选择:">
                <el-select
                  v-model="addfacilitygroupId"
                  placeholder="选择羊舍来选择某个羊圈"
                  clearable
                  filterable
                  @change="getfacilityList"
                >
                  <el-option
                    v-for="(item, index) in facilitygroupList"
                    :key="index + 'facgroup'"
                    :label="item.groupName"
                    :value="item.facilityGroupId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="facilityList.length>0" :span="12">
              <el-form-item label="羊圈选择:">
                <el-select
                  v-model="addfacilityId"
                  placeholder="选择羊圈来批量选择个体"
                  clearable
                  filterable
                  @change="getBionbyfac"
                >
                  <el-option
                    v-for="(item, index) in facilityList"
                    :key="index + 'fac'"
                    :label="item.facilityName"
                    :value="item.facilityId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="nowChanceStau === 'add'">
            <el-col :span="24">
              <el-form-item
                label="个体名称:"
                prop="bionIdList"
                :rules="[{
                  required: true, message: '请选择个体', trigger: ['blur','change']
                }]"
              >
                <el-select
                  v-model="formData.bionIdList"
                  multiple
                  placeholder="请选择"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="(item, index) in bionIdList"
                    :key="index + 'bionId'"
                    :label="item.name"
                    :value="item.bionId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="nowChanceStau === 'edit'">
            <el-col :span="24">
              <el-form-item
                label="个体名称:"
                prop="bionId"
                :rules="[{
                  required: true, message: '请选择个体', trigger: ['blur','change']
                }]"
              >
                <el-select
                  v-model="formData.bionId"
                  placeholder="请选择"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="(item, index) in allbionIdList"
                    :key="index + 'allbionId'"
                    :label="item.name"
                    :value="item.bionId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="疫苗名称:"
                prop="vaccinumId"
                :rules="[{
                  required: true, message: '请选择疫苗', trigger: ['blur','change']
                }]"
              >
                <el-select v-model="formData.vaccinumId" placeholder="请选择" clearable filterable>
                  <el-option
                    v-for="(item, index) in vaccinumList"
                    :key="index + 'vaccinum'"
                    :label="item.vaccinumName"
                    :value="item.vaccinumId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="接种日期:"
                prop="vaccinationDate"
                :rules="[{
                  required: true, message: '请选择接种日期', trigger: ['blur','change']
                }]"
              >
                <el-date-picker v-model="formData.vaccinationDate" type="datetime" placeholder />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="不良反应:"
                prop="untowardEffect"
              >
                <el-input v-model="formData.untowardEffect" placeholder="请填写不良反应" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="model-cancel-btn" @click="addDialog = false">取 消</el-button>
          <el-button type="primary" class="model-submit-btn" @click="confirm()">确 定</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import Pagination from "@/components/Pagination";
import ActionBar from "@/components/ActionBar/index";
import BaseMainSlot from "@/components/BaseMainSlot/baseone.vue";
import { mymixin } from "@/utils/mixin";
import req from "@/api/digital-production/health-management/individual-blight-record/index";
import { getToken } from "@/utils/auth";
export default {
  name: "VaccinationManagement",
  components: {
    Pagination,
    ActionBar,
    BaseMainSlot
  },
  mixins: [mymixin],
  data() {
    return {
      // 批量添加相关
      addfacilitygroupId: '',
      facilitygroupList: [],
      facilityList: [],
      addfacilityId: '',
      // 搜索条件
      bionIdName: "",
      bionIdNumber: "",
      vaccinationDate: "",
      tableData: [], // 疫病数组
      addDialog: false,
      formData: {},
      bionIdList: [], // 个体信息数组
      allbionIdList: [],
      vaccinationIdList: [],
      vaccinumList: [],
      length: 0,
      StartTime: "",
      EndTime: "",
      eagTag: ""
    };
  },
  watch: {
    nowChanceStau(newval) {
      if (newval === "add") {
        // alert("1")
        this.addUser();
      } else if (newval === "edit") {
        // alert("1")
        this.addUser();
      } else if (newval === "del") {
        // this.deleteRow();
      } else if (newval === "cancel") {
        this.$refs.tableRef.setCurrentRow();
        this.nowChanceStau = "";
      }
    },
    addDialog(v) {
      // alert(this.nowChanceStau);
      if (this.nowChanceStau === "edit") {
        // this.nowChanceStau = "";
      }
      /* if (this.nowChanceStau === "add") { */
      this.$nextTick(() => {
        this.$refs["addForm"].clearValidate();
      });
      /*  } */
    }
  },
  async created() {
    await this.querybionId();
    await this.queryVaccinumAll();
    await this.queryPageList();
    this.getfacilitygroupList()
  },
  methods: {
    // 查询表格
    async queryPageList() {
      await req
        .queryPageVaccinationList({
          page: this.currentPage,
          size: this.pageSize,
          entity: {
            breed: "HuSheep",
            eagtag: this.eagtag,
            // vaccinationDate: this.vaccinationDate,
            startTime: this.StartTime,
            endTime: this.EndTime,
            name: this.bionIdName || this.bionIdNumber,
            eagTag: this.eagTag
          }
        })
        .then(res => {
          if (res.code === 1) {
            let data = res.data || {};
            this.length = data.totalElements;
            let result = data.content || [];
            this.tableData = result;
            if (this.tableData.length > 0) {
              this.tableData.map(item => {
                if (item.vaccinumId) {
                  let index = this.vaccinumList.findIndex(
                    a => a.vaccinumId === item.vaccinumId
                  );
                  if (index !== -1) {
                    item.vaccinumName = this.vaccinumList[index][
                      "vaccinumName"
                    ];
                  }
                }
              });
            }
            /* if (this.tableData.length === 0) {
              this.addblankmet();
            } */
          }
        });
    },
    // 查询所有设施组
    getfacilitygroupList() {
      req.queryFacilitygroupAll().then(res => {
        if (res.code === 1) {
          let data = res.data || [];
          this.facilitygroupList = data;
        }
      });
    },
    // 条件查询设施
    getfacilityList(id) {
      this.addfacilityId = ""
      req.queryFacilitybycondition(id).then(res => {
        if (res.code === 1) {
          let data = res.data || [];
          this.facilityList = data;
          if (data === []) {
            this.$message.warning("暂无羊圈信息")
          }
        } else {
          this.$message.error("获取羊圈失败！")
        }
      });
    },
    // 条件查询个体信息-通过设施id
    getBionbyfac(id) {
      this.$set(this.formData, 'bionIdList', [])
      this.bionIdList = []
      req.getBionbyfac(id).then(res => {
        if (res.code === 1) {
          this.formData.bionIdList = []
          let data = res.data || [];
          this.bionIdList = data;
          let selectedidlist = []
          // console.log(data)
          if (data && data.length > 0) {
            data.forEach(item => {
              selectedidlist.push(item.bionId)
            });
          }
          this.$set(this.formData, 'bionIdList', selectedidlist)
        }
      });
    },
    // 查询个体的信息
    async querybionId() {
      await req
        .queryBionAll({
          breed: "HuSheep"
        })
        .then(res => {
          if (res.code === 1) {
            let data = res.data || [];
            this.allbionIdList = data;
          }
        });
    },
    // 查询疫苗信息
    async queryVaccinumAll() {
      await req.queryVaccinumAll({}).then(res => {
        if (res.code === 1) {
          let data = res.data || [];
          this.vaccinumList = data;
        }
      });
    },
    // 添加或者修改提交
    confirm() {
      this.$refs["addForm"].validate(valid => {
        if (valid) {
          this.formData.organizationNo = parseInt(getToken("organizationNo"));
          if (this.nowChanceStau === "edit") {
            let editpar = {
              ...this.formData
            }
            delete editpar.bionIdList
            req.editVaccination(editpar).then(res => {
              if (res.code === 1) {
                this.$message.success("修改成功！");
                this.addDialog = false;
                this.addActive = true;
                this.nowChanceStau = "";
                this.formData = {};
                this.queryPageList();
              } else {
                this.$message.error("修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            // let bionlist = this.formData.bionIdList
            // if(bionlist){

            // }else{
            //   this.$message.warning("请选择一个")
            // }
            let addpar = {
              ...this.formData
            }
            delete addpar.bionId
            console.log(this.formData)
            // return
            req.addVaccination(addpar).then(res => {
              if (res.code === 1) {
                this.$message.success("新增成功！");
                this.addDialog = false;
                this.addActive = true;
                this.nowChanceStau = "";
                this.formData = {};
                this.queryPageList();
              } else {
                this.$message.error("新增失败！");
              }
            });
          }
        } else {
          this.$message.error("请将信息填写完整！！！");
          return false;
        }
      });
    },
    addUser() {
      this.addDialog = true;
    },
    handleSelectionChange(list) {
      this.vaccinationIdList = [];
      let notvalue = true;
      this.vaccinationIdList = list.map(item => {
        if (item.vaccinationId) {
          return item.vaccinationId;
        } else {
          notvalue = false;
          return "";
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
        return;
      }
      if (this.vaccinationIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      req
        .delVaccination({
          vaccinationIdList: this.vaccinationIdList
        })
        .then(res => {
          if (res.code === 1) {
            this.$message.success("删除成功");
            this.queryPageList();
          } else {
            this.$message.error("删除失败");
          }
        });
    },

    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.queryPageList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.queryPageList();
    },
    handleEdit(row) {
      if (row.vaccinationId) {
        this.formData = row;
        this.editActive = true;
        this.saveActive = false;
        this.cancelActive = true;
      }
    },
    cancel() {
      this.$refs.tableRef.setCurrentRow();
      this.$refs.tableRef.clearSelection();
      this.nowChanceStau = "";
      this.addActive = true;
      this.cancelActive = false;
      this.editActive = false;
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";
::v-deep .el-table {
  overflow: auto;
}
::v-deep .el-dialog__body {
  background: #f0f3f7;
  color: #fff;
  .el-input {
    width: 100%;
  }
  .el-select {
    //充满父元素（el-col）
    width: 100%;
  }
}
// 弹框底下按钮样式
.model-submit-btn{
background-color: #006e91;
    border-color: #006e91;
    &:hover{
      background-color: #006f91b9;
    border-color: #006f91b9;
    }
}
.model-cancel-btn{
  &:hover{
      background-color: #006f9128;
    border-color: #006e91;
    color:#006e91
    }
}
</style>
